package com.binecy.service;

import com.binecy.bean.Order;
import com.binecy.bean.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@Service
public class OrderService {
    private static final Logger logger = LoggerFactory.getLogger(OrderService.class);

    @Autowired
    private WebClient.Builder webClientBuilder;

    @Autowired
    private RestTemplate restTemplate;


    public Order  getById2() {
        ResponseEntity<User> res = restTemplate.getForEntity("http://user-service/user/1", User.class);
        User u = res.getBody();

        Order o = new Order();
        o.setUserName(u.getName());
        return o;
    }


    public Mono<Order> getById() {
        Mono<User> userMono =  webClientBuilder.build()
                .get()
                .uri("http://user-service/user/" + 1)
                .retrieve()
                .bodyToMono(User.class);
        logger.info("getUser end");

        return Mono.just(new Order()).zipWith(userMono, (o, u) -> {
            o.setUserName(u.getName());
            return o;
        });
    }

    public Mono<Order> getOrder(long userId) {
        logger.info("getUser start");

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        Mono<User> userMono =  WebClient.create()
                .get()
                .uri("http://localhost:9002/user/" + userId)
                .retrieve()
                .bodyToMono(User.class);
        logger.info("getUser end");

        return Mono.just(new Order()).zipWith(userMono, (o, u) -> {
            o.setUserName(u.getName());
            return o;
        });

//        Flux.fromArray().concatMap()

    }
}
